<?php
class MisApi{
    private $xml_file;
    /**
     *get data by api function 
     *@param api function name;
     *@param array ,e.g array('CO_CODE'=>'11','PGM_ID'=>'22');
     *@return array object if success or return false
     */
    public function getDataByApiBak($api_function,$array){
        $data_array = $this->parseXml($this->xml_file);
        if(!empty($data_array))
        {
            if(array_key_exists($api_function,$data_array))
            {
                $ret = $data_array[$api_function];
                $url_para = 'API_CODE='.MisApiConfig::$api_code;
                if(!empty($array))
                {
                    foreach($array as $key => $val)
                    {
                        $url_para = $url_para.'&'.$key.'='.$val;
                    }
                }

                $curl = curl_init();
                curl_setopt($curl,CURLOPT_URL,$ret);
                curl_setopt($curl,CURLOPT_HEADER,0);
                curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
                curl_setopt($curl,CURLOPT_POST,true);
                curl_setopt($curl,CURLOPT_POSTFIELDS,$url_para);
                
                $info = curl_exec($curl);
                
                if(!empty($info))
                {
                    if($api_function == 'getTransactions')
                    {
                        $temp_arr = array();
                        $new_xml = MisApiConfig::$mis_api_download_path . $api_function.'.xml';
                        file_put_contents($new_xml,$info);
                        //$this->load_xml = $new_xml;
                        //$ret_array = $this->getTrans($new_xml,$temp_arr);
                        //$result = $ret_array;
                        //$result = new ArrayObject($ret_array);
                        $result = $new_xml;
                    }
                    else
                    {
                        $result = $this->getXmlObject($info);
                    }
                    return $result;
                }
                else
                {
                    return FALSE;
                }
                curl_close($curl);
            }
            else
            {
                return FALSE;
            }
        }
        else return FALSE;
    }

	public function getDataByApi($function,$param){

		# For MIS Debugging
		if($function=='sendJobReceive' && MisApiConfig::$mis_debug){
			return $this->getXmlObject('<?xml version="1.0" encoding="utf-8"?><JobReceive><INFO>"RECEIVE" IS SENT</INFO></JobReceive>');
		}
		if($function=='sendJobPublish' && MisApiConfig::$mis_debug){
			return $this->getXmlObject('<?xml version="1.0" encoding="utf-8"?><JobPublish><INFO>"PUBLISH" IS SENT</INFO></JobPublish>');
		}

		$param ['API_CODE'] = $function;
		#if(isset($param['PGM_ID'])) {
		#	$param['CO_CODE'] = MisApiConfig::$api_code;
		#}
		$url = CommonUtils::url_add_param(AC::MIS_API,$param); //.'?API_CODE='.$function,

		$file = MisApiConfig::$mis_api_download_path.'/'.md5($url).'.xml';
		echo "Get MIS Data URL: $url \n file : $file \n";
		if(file_exists($file)){
			return $this->getXmlObject(file_get_contents($file));
		}

		$request = new HttpRequest();
		$request->setUrl($url);
		$request->send();
		if($request->getResponseCode()!=200) throw new Exception("MIS API($url) Error: MIS Return Code => ".$request->getResponseCode());// return false;

		$info = $request->getResponseBody();
		#$info = preg_replace('#<Air_Date>.+</Air_Date>#isU','',$info);  // remove air_date tag for test
		if(preg_match('#<ERROR>#i',$info)) throw new Exception("MIS API($url) Return Error:\n".$info); //return false;

		file_put_contents($file,$info);
		return $this->getXmlObject($info);
	}

    function __construct($xmlfile=null){
        if($xmlfile== null)
        {
            $xmlfile = MisApiConfig::$mis_config_xml;
        }
        $this->xml_file = $xmlfile;
    } 

    private function getXmlObject($xml)
    {
        return simplexml_load_string($xml);
    }

    private function parseXml($xml){
        $array = array();
        if (file_exists($xml)) {
            $xml = simplexml_load_file($xml);
            foreach($xml->api as $api){
                $api_name =(array)$api['name'];
                $api_mapping = (array)$api->mapping;
                $array[$api_name[0]] = $api_mapping[0];
            } 
        } 

        return $array;

    }

/*
    private function getTrans($xml,$data_array){
        $read = new XMLReader();
        $result = array();
        if(empty($xml))
        {
            return $result;
        }
        $read->open($xml);
        $temp = array();
        $key = '';

        while($read->read())
        {
            $value = $read->value;

            if($read->nodeType == XMLReader::ELEMENT)
            {
                $key = $read->name;
            }

            if($read->nodeType == XMLReader::TEXT && !empty($value))
            {
                $temp[$key] = $value;
            }
            if($read->nodeType == XMLReader::END_ELEMENT && $read->name == 'Logging')
            {
               // $result[] = $temp;
               // $temp = array();


                if(empty($data_array))
                {
                    $result[] = $temp;
                    $temp = array();
                }
                else
                {
                    if(!empty($temp))
                    {
                        foreach($temp as $val)
                        {
                            foreach($data_array as $data)
                            {
                                if($val === $data)
                                {
                                    $result[] = $temp;
                                    $temp = array();
                                }
                            }
                        }
                    }
                }

            }
        }
        $read->close();
        return $result;
    }
 */
   
/*
    public function getItemsByTable($xml,$table)
    {
        $table_array = array();
        if(empty($table))
        {
            return false;
        }
        else
        {
            $table_array[] = $table;
        }
        $ret = $this->getTrans($xml,$table_array);
        return empty($ret) ? false : new ArrayObject($ret);
    }


    public function getItemsByAction($xml,$action)
    {
        $action_array = array();
        if(empty($action))
        {
            return false;
        }
        else
        {
            $action_array[] = $action;
        }
        $ret = $this->getTrans($xml,$action_array);
        return empty($ret) ? false :  new ArrayObject($ret);
    }


    public function getItems($xml)
    {
        $table_array = array();
        $ret = $this->getTrans($xml,$table_array);
        return empty($ret) ? false :  new ArrayObject($ret);
    }
 */

}
?>
